package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.service.SpecParamService;
import com.leyou.item.service.SpuDetailService;
import com.leyou.item.service.SpuService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.Map;

@Service
public class SpuDetailServiceImpl extends ServiceImpl<SpuDetailMapper, SpuDetail> implements SpuDetailService {

    private  SpuMapper spuMapper;
    private  SpecParamService specParamService;
    private SpuService spuService;

    public SpuDetailServiceImpl(SpuMapper spuMapper, SpecParamService specParamService) {
        this.spuMapper = spuMapper;
        this.specParamService = specParamService;
    }

    @Override
    public List<SpecParamDTO> querySpecParam(Long id, Boolean searching) {
        //根据id查询specDetail
        SpuDetail detail = getById(id);
        Map<Long, Object> specValues = JsonUtils.toMap(detail.getSpecification(), Long.class, Object.class);


        //根据id查询spu，获取商品分类信息
        Spu spu = spuMapper.selectById(id);
        //根据分类id查询规格参数的集合，如果searching不能为空，还要加上searching条件
            List<SpecParamDTO> params = specParamService.querySpecParam(spu.getCid3(), null, searching);
        for (SpecParamDTO param : params) {
            param.setValue(specValues.get(param.getId()));
        }
        return params;
    }

    @PutMapping
    public ResponseEntity<Void>updateGoods(@RequestBody SpuDTO spuDTO){
        spuService.updateGoods(spuDTO);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }
}